const MongoClient = require('mongodb').MongoClient;
const url = "mongodb://taosha_user:apyl8XWP6LSW4JHs@101.35.6.34:27722/taosha";

async function main() {
  const client = await MongoClient.connect(url, {useNewUrlParser: true, useUnifiedTopology: true});
  const db = client.db('taosha');


  let topics = await db.collection('topics')
    .find(
      {author_name: '鱼塘热榜', real_author_name: {$ne: '鱼塘精选'}}
    )
    .toArray();


  for (let i = 0; i < topics.length; i++) {
    let topic = topics[i];
    let real_author_name = topic.real_author_name;
    if (real_author_name == '掘金热榜') {
      real_author_name = '掘金'
    } else if (real_author_name == 'InfoQ热榜') {
      real_author_name = 'InfoQ'
    } else if (real_author_name == '界面新闻热榜') {
      real_author_name = '界面新闻'
    } else if (real_author_name == '龙腾网') {
      real_author_name = '龙腾网'
    } else if (real_author_name == '思否热榜') {
      real_author_name = '思否'
    } else if (real_author_name == '看看热榜') {
      real_author_name = '看看新闻'
    } else if (real_author_name == '指股网热榜') {
      real_author_name = '指股网'
    }

    let author = await db.collection('users').findOne({nickname: real_author_name});
    if (!author) {
      console.log(real_author_name, 'xxxxx');
      continue;
    }
    let author_id = author._id.toString();
    let author_name = author.nickname;
    let author_avatar = author.avatar_url;
    try {
      let result = await db.collection('topics').updateOne({_id: topic._id}, {
        $set: {
          author_id,
          author_name,
          author_avatar,
        },
        $unset: {real_author_name: ''}
      });
    } catch (e) {
      console.error(e.message, topic.real_author_name);
      await db.collection('topics').deleteOne({_id: topic._id});
    }
  }

  client.close();

}

main();
